package com.skp.shaphan.sql;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class ValueToText {
	private static ValueToText instance = null;
	private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	private static DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
	
	
	public static ValueToText getInstance() {
		if(instance == null) {
			instance = new ValueToText();
		}
		return instance;
	}
	public String convert(Object value) throws SQLException, IOException {
		String stringValue;
		if(value == null) {
			return "<null>";
		} else {
			if(value instanceof Double) {
				DecimalFormat f = new DecimalFormat();
				stringValue = f.format(value);
			} else if (value instanceof Timestamp) {
				Calendar c = Calendar.getInstance();
				c.setTimeInMillis(((Timestamp) value).getTime());
				if(c.get(Calendar.HOUR) > 0 || c.get(Calendar.MINUTE) > 0 || c.get(Calendar.SECOND) > 0) {
					stringValue = dateTimeFormat.format(c.getTime());
				} else {
					stringValue = dateFormat.format(c.getTime());
				}
			} else if (value instanceof oracle.sql.TIMESTAMP) {
				Calendar c = Calendar.getInstance();
				c.setTimeInMillis(((oracle.sql.TIMESTAMP) value).timestampValue().getTime());
				if(c.get(Calendar.HOUR) > 0 || c.get(Calendar.MINUTE) > 0 || c.get(Calendar.SECOND) > 0) {
					stringValue = dateTimeFormat.format(c.getTime());
				} else {
					stringValue = dateFormat.format(c.getTime());
				}
			} else if (value instanceof oracle.sql.CLOB) {
				oracle.sql.CLOB clob = (oracle.sql.CLOB) value;
				InputStream stream = clob.getAsciiStream();
				byte[] buffer = new byte[256];
				int sizeRead = stream.read(buffer);
				stringValue = new String(buffer);
				if(sizeRead == buffer.length) {
					stringValue = stringValue.concat("...");
				}
			} else {
				stringValue = value.toString();
				if(!(value instanceof String)) {
					System.out.println(value.getClass().getName() + " -- " + value);
				}
			}
			return stringValue;
		}
	}
}
